package com.zoro.barn.business.service.system.business.roleuser.service;

import com.zoro.barn.business.service.system.business.roleuser.dao.BarnRoleUserMapper;
import com.zoro.barn.business.service.system.business.roleuser.entity.BarnRoleUser;
import com.zoro.barn.commons.tools.string.IDs;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhaoxingwu
 */
@Service
public class BarnRoleUserService {

    @Resource
    private BarnRoleUserMapper barnRoleUserMapper;

    /**
     * 向用户添加角色
     *
     * @param pid     pid
     * @param roleIds role id
     */
    @Transactional(rollbackFor = Exception.class)
    public void addRole(String pid, String[] roleIds) {
        if (StringUtils.isBlank(pid) || roleIds == null || roleIds.length == 0) {
            return;
        }

        // 检查是否已经存在
        Set<String> newRole = new HashSet<>();
        for (String roleId : roleIds) {
            if (StringUtils.isBlank(roleId)) {
                continue;
            }
            int c = this.barnRoleUserMapper.haseRole(pid, roleId);
            if (c == 0) {
                newRole.add(roleId);
            }
        }

        if (CollectionUtils.isEmpty(newRole)) {
            return;
        }

        List<BarnRoleUser> data = new ArrayList<>();
        for (String roleId : newRole) {
            BarnRoleUser ru = new BarnRoleUser();
            ru.setPid(IDs.uuid());
            ru.setRoleId(roleId);
            ru.setUserId(pid);
            data.add(ru);
        }
        this.barnRoleUserMapper.insertBatch(data);


    }

    /**
     * 删除用户与角色关系
     *
     * @param roleId role
     * @param userId user
     */
    public void delete(String roleId, String userId) {

        this.barnRoleUserMapper.delete(roleId, userId);

    }

}
